import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import Course from '@/views/Course.vue'
import CoursePreview from '@/views/CoursePreview.vue'
import ChapterPreview from '@/views/ChapterPreview.vue'
import VideoCourse from '@/views/VideoCourse.vue'
import VideoPreview from '@/views/VideoPreview.vue'
import Profile from '@/views/Profile.vue'
import Todolist from '@/views/Todolist.vue'
import UserManagement from '@/views/UserManagement.vue'  // 添加这行

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { title: '笔记列表 - Course List' }
  },
  {
    path: '/course',
    name: 'Course',
    component: Course,
    meta: { title: '创建笔记', requiresAuth: true }
  },
  {
    path: '/course-preview',
    name: 'CoursePreview',
    component: CoursePreview,
    meta: { title: '笔记预览' }
  },
  {
    path: '/chapter-preview',
    name: 'ChapterPreview',
    component: ChapterPreview,
    meta: { title: '章节预览' }
  },
  {
    path: '/video-course',
    name: 'VideoCourse',
    component: VideoCourse,
    meta: { title: '创建视频课程', requiresAuth: true }
  },
  {
    path: '/video-preview',
    name: 'VideoPreview',
    component: VideoPreview,
    meta: { title: '视频预览' }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: { title: '个人中心', requiresAuth: true }
  },
  {
    path: '/todolist',
    name: 'Todolist',
    component: Todolist,
    meta: { title: '计划列表', requiresAuth: true }
  },
  {
    path: '/user-management',
    name: 'UserManagement',
    component: UserManagement,
    meta: { title: '用户管理', requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 设置页面标题
router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '讲懂笔记'
  
  // 检查是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const currentUser = localStorage.getItem('currentUser')
  
  if (requiresAuth && !currentUser) {
    // 需要认证但未登录，重定向到首页
    next('/')
  } else {
    next()
  }
})

export default router